package models

import (
	
	"encoding/json"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
	_ "github.com/astaxie/beego/cache/redis"
)

var redisClient cache.Cache
var enableRedis, _ = beego.AppConfig.Bool("enableRedis")
var redisTime, _ = beego.AppConfig.Int("redisTime")

var YzmClient cache.Cache

func init() {
	if enableRedis {
		config := map[string]string{
			"key":     beego.AppConfig.String("redisKey"),
			"conn":    beego.AppConfig.String("redisConn"),
			"dbNum":   beego.AppConfig.String("redisDbNum"),
			"pawword": beego.AppConfig.String("redisPwd"),
		}
		bytes, _ := json.Marshal(config)
		redisClient, err = cache.NewCache("redis", string(bytes))
		YzmClient, _ = cache.NewCache("redis", string(bytes))

		if err != nil {
			beego.Error("连接redis数据库err:", err)
		} else {
			beego.Info("连接redis数据库成功")
		}
	}
}

type cacheDb struct{}

var CacheDb = &cacheDb{}

func (c cacheDb) Set(key string, value interface{}) {
	if enableRedis {
		v, _ := json.Marshal(value)
		err := redisClient.Put(key, v, time.Second*time.Duration(redisTime))
		if err != nil {
			beego.Warn("redis put data err:", err)
		}
	}
}

func (c cacheDb) Get(key string, obj interface{}) bool {
	if enableRedis {
		if redisstr := redisClient.Get(key); redisstr != nil {
			beego.Info("从redis中读取消息", "key:", key)
			data, ok := redisstr.([]uint8)
			if !ok {
				beego.Warn("读取redis数据失败", "key:", key)
				return false
			}
			err := json.Unmarshal([]byte(data), obj)
			if err != nil {
				beego.Warn("读取redis数据失败", "key:", key)
				return false
			}
			return true
		}
	}
	beego.Warn("读取redis数据失败", "key:", key)
	return false
}
